package com.example.inventoryapp.ui

import android.app.Application
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory
import androidx.lifecycle.createSavedStateHandle
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.inventoryapp.InventoryApplication
import com.example.inventoryapp.ui.home.HomeViewModel
import com.example.inventoryapp.ui.item.ItemDetailsViewModel
import com.example.inventoryapp.ui.item.ItemEditViewModel
import com.example.inventoryapp.ui.item.ItemEntryViewModel

/**
 * 提供了一个工厂类，用于为整个库存应用程序创建视图模型的实例。
 */
object AppViewModelProvider {
    val Factory = viewModelFactory {
        // ItemEntryViewModel 需注入 SavedStateHandle
        initializer {
            ItemEditViewModel(
                this.createSavedStateHandle()
            )
        }
        // Initializer for ItemEntryViewModel
        initializer {
            ItemEntryViewModel()
        }

        // ItemDetailsViewModel 保持代参数初始化
        initializer {
            ItemDetailsViewModel(
                this.createSavedStateHandle()
            )
        }

        // “主视图模型初始化器”
        initializer {
            HomeViewModel()
        }
    }
}

/**
 * 扩展函数用于查询 [Application] 对象，并返回一个实例的 * [InventoryApplication] 。
 */
fun CreationExtras.inventoryApplication(): InventoryApplication =
    (this[AndroidViewModelFactory.APPLICATION_KEY] as InventoryApplication)